<!--
 * @Description: 选择影院后展示电影场次
 * @Author: Kerwin
 * @Date: 2025-04-27 17:30:11
 * @LastEditTime: 2025-05-30 12:01:39
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="container">
    <view class="top">
      <!-- 背景图片盒子 -->
      <view class="bjbox"> </view>
      <!-- 影院盒子 -->
      <view class="yybox">
        <view class="yybox-l">
          <view class="yybt">{{ cinameInfo.cinemaName }}</view>
          <view style="margin: 15rpx 0">{{ cinameInfo.cinemaAddress }}</view>
          <view class="wzbox">
            <view style="margin-right: 20rpx"
              ><u-icon name="map" color="#999" size="28"></u-icon
              ><text>{{
                formatDistance(Number(cinameInfo.distance))
              }}</text></view
            >
            <view
              ><u-icon name="phone" color="#999" size="28"></u-icon>
              <text class="overwz" style="width: 350rpx"
                >电话:{{ cinameInfo.cinemaPhone }}</text
              ></view
            >
            <!-- 重新加载图标 -->
            <u-icon
              color="black"
              name="reload"
              size="40"
              @click="getAllSession(cinemaId, '')"
              style="cursor: pointer"
            ></u-icon>
          </view>
        </view>
        <view class="yybox-r">
          <u-image
            @click="showMap = true"
            width="55rpx"
            height="55rpx"
            :src="adress"
          ></u-image>
        </view>
      </view>
      <!-- 展示电影信息-->
      <view class="dyGroups">
        <!-- 展示所有的电影图片 -->
        <view class="tpbox">
          <van-image
            width="180rpx"
            height="260rpx"
            :src="movieInfo.posterUrl"
          />
        </view>
        <!-- 当前显示的电影信息 -->
        <view class="dyInfo">
          <view class="box1">
            <text class="wz1">{{ movieInfo.movieName }}</text>
            <text style="color: #ff6c18">{{ movieInfo.grade }}分</text>
          </view>
          <view class="overwz wz2">{{ movieInfo.director }}</view>
        </view>
      </view>
    </view>
    <view style="color: #ccc; font-size: 20rpx; margin-bottom: 20rpx">
      <u-button @click="handleGoIndex" type="warning">重新选择电影</u-button>
    </view>
    <!-- 日期展示 -->
    <view class="middle" v-if="dateList.length > 0">
      <van-tabs
        :active="currentTabIndex"
        @change="handleDateChange"
        color="#FF6C18"
        title-inactive-color="#999"
        title-active-color="#FF6C18"
      >
        <van-tab
          :title="`${sj.weekName} ${sj.name}`"
          v-for="sj in dateList"
        ></van-tab>
      </van-tabs>
    </view>
    <view class="footer">
      <template v-if="filteredSessions.length > 0">
        <view class="itembox" v-for="cc in filteredSessions" :key="cc.showId">
          <!-- 展示时间 -->
          <view class="item1">
            <view
              style="
                color: #333;
                font-size: 40rpx;
                font-weight: bold;
                margin-bottom: 10rpx;
              "
            >
              {{ cc.showTime.split(' ')[1].slice(0, 5) }}
            </view>
            <view class="hswz"> {{ cc.stopShowTime }}散场 </view>
          </view>
          <view class="item2">
            <view style="color: #333; margin-bottom: 20rpx">{{
              cc.showVersionType
            }}</view>
            <view class="hswz overwz">{{ cc.hallName }}</view>
          </view>
          <view class="item3">
            <view class="hswz pj">票价¥{{ cc.showPrice }}</view>
            <view class="xjje"
              >¥{{ shopMode == 6 ? cc.showPrice : cc.userMoney }}
              <text style="font-size: 14rpx; margin: 5rpx 5rpx 0 0">起</text>
              <template v-if="cc.userScoreMoney != 0">
                <text>{{ shopMode == 6 ? '-' : '+' }} </text>
                <view style="margin: 0 5rpx">
                  <u-image
                    width="27rpx"
                    height="20rpx"
                    src="../../static/yhq.png"
                  ></u-image>
                </view>
                {{ cc.userScoreMoney }}
              </template>
            </view>
            <view class="sqje" v-if="cc.userScoreMoney != 0"
              >立省{{ cc.userScoreMoney }}元</view
            >
          </view>
          <view class="item4">
            <u-button
              v-if="!cc.isStopped"
              @click="handleBuyTicket(cc)"
              type="primary"
              style="width: 114rpx; height: 48rpx; font-size: 20rpx"
              >购票</u-button
            >
            <u-button
              v-else
              disabled
              style="
                width: 114rpx;
                height: 48rpx;
                font-size: 20rpx;
                font-weight: bold;
              "
              >停售</u-button
            >
          </view>
        </view>
        <u-back-top :scroll-top="scrollTop"></u-back-top>
      </template>
      <view style="font-size: 30rpx; text-align: center; color: #999" v-else
        >暂无场次</view
      >
    </view>
  </view>
  <!-- 地图弹出框 -->
  <van-popup
    v-model:show="showMap"
    round
    position="bottom"
    :style="{ height: '30%' }"
  >
    <view class="mapbox">
      <van-button class="btn" @click="openGMap" type="default"
        >高德地图</van-button
      >
      <van-button class="btn" @click="openBMap" type="default"
        >百度地图</van-button
      >
      <van-button class="btn" @click="openTMap" type="default"
        >腾讯地图</van-button
      >
      <van-button class="btn" @click="copyMap" type="default"
        >复制地址</van-button
      >
      <van-button class="btn btn2" type="default" @click="showMap = false"
        >取消</van-button
      >
    </view>
  </van-popup>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { movieApi } from '@/api'
import { bMapTransQQMap } from '@/utils'
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onReachBottom,
  onPageScroll
} from '@dcloudio/uni-app'
import {
  IMovieInfo,
  ICinemaInfo,
  ISession
} from '@/packageF/components/movieInterface'
import adress from '@/static/xfl/adress.svg'
const scrollTop = ref(0)
//地图展示
const showMap = ref(false)
// 添加一个响应式的时间戳变量
let animationFrameId: number
// 当前时间戳
const currentTimeStamp = ref(Date.now())
const cinameInfo = ref<ICinemaInfo>({
  cinemaAddress: '',
  cinemaId: 0,
  cinemaName: '',
  cinemaPhone: '',
  cityId: 0,
  latitude: 0,
  longitude: 0,
  regionId: 0,
  regionName: '',
  distance: ''
})
const movieInfo = ref<IMovieInfo>({
  movieName: '',
  grade: '',
  duration: '',
  movieType: '',
  posterUrl: '',
  publishDate: '',
  intro: '',
  cast: '',
  director: '',
  publishStatus: '',
  movieId: ''
})
const cinemaId = ref()
const sessionList = ref<ISession[]>([])
const showSessionList = ref<ISession[]>([])
const dateList = ref<{ name: string; weekName: string }[]>([])
const currentTabIndex = ref(0)
// 模式
const shopMode = ref(JSON.parse(uni.getStorageSync('hyType')).id)

onShow(() => {
  movieInfo.value = JSON.parse(uni.getStorageSync('movieData'))
  movieInfo.value.movieType = movieInfo.value.movieType.replaceAll('|', ',')
  cinameInfo.value = JSON.parse(uni.getStorageSync('cinemaData'))
  cinemaId.value = cinameInfo.value.cinemaId
  getAllSession(cinemaId.value, '')
  startRealTimeCheck()
})
onHide(() =>
  // cancelAnimationFrame取消未执行的RAF回调
  cancelAnimationFrame(animationFrameId)
)
//页面卸载时清除缓存
onUnload(() => {
  // uni.removeStorageSync('cinemaData')
})

// 计算属性：根据 currentTabIndex 获取当前选中的日期
const currentDate = computed(() => {
  return dateList.value[currentTabIndex.value]?.name || ''
})
// 计算属性：动态筛选当前日期的场次
const filteredSessions = computed(() => {
  if (!currentDate.value) return []
  const now = new Date(currentTimeStamp.value)
  return showSessionList.value
    .filter((item) => {
      const [datePart] = item.showTime.split(' ')
      const [, month, day] = datePart.split('-')
      return `${month}-${day}` === currentDate.value
    })
    .map((item) => ({
      ...item,
      //是否停止售卖
      isStopped:
        now >= new Date(parseDateForIOS(item.stopSellTime).getTime() - 1000)
    }))
})
// 高精度实时检测（每帧检查）
const startRealTimeCheck = () => {
  const check = () => {
    currentTimeStamp.value = Date.now() // 强制更新计算属性
    // requestAnimationFrame请求浏览器在下次重绘前执行回调函数（通常每秒60次，匹配屏幕刷新率）
    animationFrameId = requestAnimationFrame(check)
  }
  check()
}

// 获取所有场次
const getAllSession = async (cinemaId: number, time: any) => {
  uni.showLoading({ title: '加载中，请稍后', mask: true })
  try {
    const { data } = await movieApi
      .getAllSessionApi({
        movieId: movieInfo.value.movieId,
        cinemaId,
        time,
        type: shopMode.value
      })
      .finally(() => {
        uni.hideLoading()
      })
    // console.log('data', data)
    if (data.showInfor.length <= 0) {
      return
    }
    // 将场次通过开场时间排序后再计算出散场时间
    sessionList.value = data.showInfor
      .sort((a: any, b: any) => {
        return (
          parseDateForIOS(a.showTime).getTime() -
          parseDateForIOS(b.showTime).getTime()
        )
      })
      .map((ele: any) => ({
        ...ele,
        stopShowTime: calculateStopShowTime(ele.showTime, ele.duration)
      }))
    showSessionList.value = [...sessionList.value]
    // console.log('场次', sessionList.value)
    dateList.value = handleGetChangeDate(sessionList.value)
    if (dateList.value.length > 0) {
      //存储选择的场次日期名称
      const tempStr = dateList.value[0].weekName
      uni.setStorageSync('xzWeekName', tempStr)
    }
    // console.log('dateList', dateList.value)
  } catch (e) {
    console.log('获取场次error', e)
  }
}
//计算散场时间（HH:mm）
const calculateStopShowTime = (showTime: string, duration: number): string => {
  const startDate = new Date(showTime.replace(' ', 'T')) // 兼容 iOS
  const endDate = new Date(startDate.getTime() + duration * 60 * 1000)
  return `${String(endDate.getHours()).padStart(2, '0')}:${String(
    endDate.getMinutes()
  ).padStart(2, '0')}`
}
// 将带空格的日期字符串转换为 iOS 兼容的 ISO 格式，确保 new Date() 在所有设备上解析一致。
const parseDateForIOS = (dateString: string): Date => {
  // 将 "yyyy-MM-dd HH:mm:ss" -> "yyyy-MM-ddTHH:mm:ss"
  const iosCompatibleString = dateString.replace(' ', 'T')
  return new Date(iosCompatibleString)
}
// 处理日期数组，返回包含日期名称和星期名称的对象数组
const handleGetChangeDate = (arr: any) => {
  // 1. 首先从原始数组中提取出"月-日"格式的日期
  const tempArr: string[] = arr.map((ele: any) => {
    // 分割日期时间字符串，只取日期部分（忽略时间部分）
    const [datePart] = ele.showTime.split(' ')
    // 分割日期，获取月份和日
    const [, month, day] = datePart.split('-')
    // 返回"月-日"格式的字符串
    return `${month}-${day}`
  })
  // 2. 对日期数组进行去重处理
  const uniqueDates = [...new Set(tempArr)]
  // 3. 获取当前日期对象（时间部分设为0:00:00）
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  // 4. 定义中文星期名称数组（注意顺序是周日到周六）
  const weekdayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  // 5. 处理每个唯一日期，添加星期名称
  return uniqueDates.map((date, index) => {
    // 分割月日
    const [month, day] = date.split('-')
    // 创建当前年份的日期对象
    const dateObj = new Date(
      now.getFullYear(),
      parseInt(month) - 1,
      parseInt(day)
    )
    // 计算与今天相差的天数
    const diffDays = Math.floor(
      (dateObj.getTime() - today.getTime()) / (1000 * 60 * 60 * 24)
    )
    let weekName = ''
    // 根据相差天数设置星期名称
    if (diffDays === 0) {
      weekName = '今天'
    } else if (diffDays === 1) {
      weekName = '明天'
    } else if (diffDays === 2) {
      weekName = '后天'
    } else {
      // 对于超过后天的日期，返回对应的星期几
      const weekdayIndex = dateObj.getDay() // getDay()返回0-6（0是周日）
      weekName = weekdayNames[weekdayIndex]
    }
    // 返回最终结果对象
    return {
      name: date, // 月-日格式的日期
      weekName: weekName // 计算得到的星期名称
    }
  })
}
// 切换日期
const handleDateChange = (index: any) => {
  currentTabIndex.value = index // 更新当前选中的标签下标
  //存储选择的场次日期名称
  const tempStr = dateList.value[index].weekName
  uni.setStorageSync('xzWeekName', tempStr)
}
//高德
const openGMap = () => {
  const { latitude, longitude, cinemaName } = cinameInfo.value
  window.location.href = `https://uri.amap.com/marker?position=${longitude},${latitude}&name=${cinemaName}&coordinate=gaode&callnative=0`
}
//百度
const openBMap = () => {
  const { latitude, longitude, cinemaName } = cinameInfo.value
  window.location.href = `http://api.map.baidu.com/marker?location=${latitude},${longitude}&title=${cinemaName}&output=html`
}
// 腾讯
const openTMap = () => {
  const { latitude, longitude, cinemaName } = cinameInfo.value
  window.location.href = `https://apis.map.qq.com/uri/v1/marker?marker=coord:${latitude},${longitude};title=${cinemaName}`
}
// 复制地址
const copyMap = () => {
  const address = cinameInfo.value.cinemaAddress
    ? cinameInfo.value.cinemaAddress
    : '地址信息不可用' // 获取地址信息，若无则显示默认文本
  uni.setClipboardData({
    data: address,
    success: () => {
      showMap.value = false
      uni.showToast({
        title: '复制成功'
      })
    },
    fail: () => {
      showMap.value = false
      uni.showToast({
        title: '复制失败',
        icon: 'none'
      })
    }
  })
}
// 点击购票按钮跳转选择座位
const handleBuyTicket = (sessionItem: any) => {
  // console.log('sessionItem', sessionItem)
  uni.navigateTo({
    url: `/packageF/pages/selectSeat/index`
  })
  uni.setStorageSync('sessionData', JSON.stringify(sessionItem))
  uni.setStorageSync('xzCinemaId', cinemaId.value)
  uni.setStorageSync('xzCinemaName', cinameInfo.value.cinemaName)
}
//返回顶部,所在的父盒子不能设置高度
onPageScroll((e: any) => {
  scrollTop.value = e.scrollTop
})
//公里转换
function formatDistance(km: number): string {
  if (km >= 1) {
    return `${km.toFixed(1)}km`
  } else {
    const meters = km * 1000
    return `${meters.toFixed(1)}m`
  }
}
// 返回首页
const handleGoIndex = () => {
  uni.reLaunch({
    url: `/packageF/pages/index/index?mode=${shopMode.value}`
  })
}
</script>

<style lang="scss" scoped>
.container {
  font-size: 24rpx;
  .hswz {
    color: #999;
  }
  .top {
    position: relative;
    .bjbox {
      width: 750rpx;
      height: 200rpx;
      background-image: url(../../static/ccbj.png);
    }
    .yybox {
      position: absolute;
      z-index: 1;
      top: 60rpx;
      left: 25rpx;
      width: 702rpx;
      height: 200rpx;
      background: #ffffff;
      border-radius: 16rpx;
      border: 1rpx solid #eee;
      padding: 0 20rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .yybox-l {
        flex-grow: 1;
        .yybt {
          color: #000;
          font-size: 32rpx;
          font-weight: bold;
        }
        .wzbox {
          color: #666;
          display: flex;
          align-items: center;
          font-size: 28rpx;
          > view {
            display: flex;
          }
        }
      }
    }
    .dyGroups {
      margin-bottom: 20rpx;
      margin-top: 80rpx;
      overflow: hidden;
      .tpbox {
        width: 180rpx;
        margin: 0 auto;
        margin-bottom: 10rpx;
      }
      .dyInfo {
        .box1 {
          text-align: center;
          font-size: 28rpx;
          margin-bottom: 10rpx;
          .wz1 {
            color: #333;
            font-weight: bold;
            padding-right: 20rpx;
          }
        }
        .wz2 {
          color: #666;
          font-size: 20rpx;
          text-align: center;
        }
      }
    }
  }
  .middle {
    margin: 0 auto;
    margin-bottom: 20rpx;
  }
  .footer {
    // height: 800rpx;
    overflow-y: scroll;
    .itembox {
      padding: 20rpx;
      width: 750rpx;
      height: 164rpx;
      background: #ffffff;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20rpx;
      .item2 {
        width: 200rpx;
      }
      .item3 {
        // width: 220rpx;
        .pj {
          text-decoration: line-through; /* 标准删除线 */
          /* 可选样式调整 */
          text-decoration-color: #999; /* 线颜色 */
          text-decoration-thickness: 1rpx; /* 线粗细 */
        }
        .xjje {
          font-size: 32rpx;
          color: #d70208;
          font-weight: bold;
          margin: 5rpx 0;
          display: flex;
          // align-items: center;
        }
        .sqje {
          width: 135rpx;
          height: 38rpx;
          line-height: 38rpx;
          text-align: center;
          background: #fef1ec;
          border-radius: 8rpx;
          border: 1rpx solid #ff6c18;
          font-size: 20rpx;
          color: #ff6c18;
          white-space: nowrap; /* 禁止文本换行 */
          overflow: hidden; /* 隐藏溢出内容 */
          text-overflow: ellipsis; /* 用省略号表示被截断的文本 */
        }
      }
    }
  }
}
.overwz {
  //   单行文本省略号
  width: 100%;
  white-space: nowrap; /* 禁止文本换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 用省略号表示被截断的文本 */
}
/* 缩小间距 */
.custom-swipe .van-swipe-item {
  padding: 10rpx !important; /* 调整右侧间距 */
}
.mapbox {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f7f8fa;

  .btn {
    width: 100%;
    height: 80rpx;
    border: none;
    background-color: #fff;
  }

  .btn2 {
    margin-top: 20rpx;
  }
}
</style>
